package com.stu.check.util;

import com.github.pagehelper.PageInfo;

import java.util.ArrayList;
import java.util.List;


public class PageInfoHelper<T> {
  private PageInfo<T> pageInfo;

  public PageInfoHelper(List<T> list, Integer pageNum, Integer pageSize) {
    if (list == null || list.size() == 0 || pageNum == null || pageSize == null) {
      pageInfo = new PageInfo<>(list);
      return;
    } else {
      pageInfo = new PageInfo<>(list);
    }

    // 总记录数
    int total = list.size();
    int divisor = total / pageSize;
    int remainder = total % pageSize;
    // 总页数
    int pages = divisor + (remainder == 0 ? 0 : 1);
    pageInfo.setTotal(total);
    pageInfo.setPages(pages);
    pageInfo.setPageSize(pageSize);

    pageNum = pageNum < 1 ? 1 : pageNum;
    pageNum = pageNum > pages ? pages : pageNum;
    pageInfo.setPageNum(pageNum);
    // 当前页面第一个元素在数据库中的行号
    int startRow = (pageNum - 1) * pageSize + 1;
    pageInfo.setStartRow(startRow);
    int endRow = (startRow + pageSize - 1) > total ? total : startRow + pageSize - 1;
    pageInfo.setEndRow(endRow);
    pageInfo.setSize(endRow - startRow + 1);

    pageInfo.setFirstPage(1);
    // 前一页
    int prePage = pageNum == 1 ? 1 : pageNum - 1;
    pageInfo.setPrePage(prePage);
    // 后一页
    int nextPage = pageNum < pages ? pageNum + 1 : pages;
    pageInfo.setNextPage(nextPage);
    pageInfo.setLastPage(pages);
    pageInfo.setIsFirstPage(pageNum == 1 ? true : false);
    pageInfo.setIsLastPage(pageNum == pages ? true : false);
    pageInfo.setHasPreviousPage(pageNum == prePage ? false : true);
    pageInfo.setHasNextPage(pageNum == nextPage ? false : true);
    pageInfo.setNavigatePages(pages);
    pageInfo.setNavigatepageNums(num2Array(pages));

    List<T> pageList = new ArrayList<>();
    for (int i = startRow - 1; i < endRow; i++) {
      pageList.add(list.get(i));
      pageInfo.setList(pageList);
    }
  }

  private int[] num2Array(int num) {
    if (num <= 0)
      return new int[]{};
    int[] arr = new int[num];
    for (int i = 0;i < num;i++)
      arr[i] = i + 1;
    return arr;
  }

  public PageInfo<T> getPageInfo() {
    return pageInfo;
  }
}
